import logging
import re
from datetime import datetime

import elasticsearch
import requests

from django.conf import settings
import json

from apps.usermanager.models import User
from apps.demomanager.models import Demo

ES_URL = settings.ES_URL

urls_key = "test"


class EsUtils(object):
    def _create_response(self, url, body):
        try:
            resp = requests.post(url, json=body)
            status = resp.json().get("_shards").get("successful")
            return status
        except Exception as e:
            logging.error(e)
            return 0
    
    def _update_response(self, url, body):
        try:
            resp = requests.post(url, json=body)
            status = resp.json().get("_shards").get("successful")
            return status
        except Exception as e:
            logging.error(e)
            return 0
    
    def _search_response(self, url, body):
        resp = requests.post(url, json=body)
        hits = resp.json().get("hits").get("hits") if resp.json().get("hits") else None
        
        if len(hits) == 0 or hits is None:
            return None
        
        source_list = []
        for hit in hits:
            source = hit.get("_source")
            highlight = hit.get("highlight")
            if not highlight is None:
                for key, value in highlight.item():
                    source[key] = value
            if source is None:
                continue
            source["id"] = hit.get("_id", -1)
            source_list.append(source)
        return source_list


class UserEs(EsUtils):
    def create(self, user: User, key_word):
        url = "{}/user/{}/{}".format(ES_URL, urls_key, str(user.id))
        body = {
            "key_word": key_word,
            "name": user.name,
            "remarks": user.detail,
            "profession": user.profession
        }
        return self._create_response(url, body)
    
    def update(self, user: User, key_word):
        url = "{}/user/{}/{}".format(ES_URL, urls_key, str(user.id))
        body = {
            "key_word": key_word,
            "name": user.name,
            "remarks": user.detail,
            "profession": user.profession
        }
        return self._update_response(url, body)
    
    def search(self, keyword, froms):
        url = "{}/user/{}/{}".format(ES_URL, urls_key, "_search")
        if not froms.isdigit():
            return None
        body = {
            "from": int(froms),
            "size": 8,
            "query": {
                "multi_match": {
                    "query": keyword,
                    "fields": ["name", "key_word", "remarks", "profession"]
                }
            },
            "highlight": {
                "fields": {
                    "name": {},
                    "remarks": {}
                }
            }
        }
        return self._search_response(url, body)


class DemoEs(EsUtils):
    def create(self, demo: Demo, indexchar):
        url = "{}/user/{}/{}".format(ES_URL, urls_key, str(demo.id))
        content = re.sub(r'<[^>]+>', "", demo.content, re.S)
        body = {
            "title": demo.title,
            "content": content,
            "creat_time": demo.creat_time.strftime("%Y-%m-%d %H:%M:%S"),
            "author": demo.author.name,
            "indexchar": indexchar
        }
        return self._create_response(url, body)
    
    def update(self, demo: Demo, indexchar):
        url = "{}/user/{}/{}".format(ES_URL, urls_key, str(demo.id))
        content = re.sub(r'<[^>]+>', "", demo.content, re.S)
        body = {
            "title": demo.title,
            "content": content,
            "creat_time": demo.creat_time.strftime("%Y-%m-%d %H:%M:%S"),
            "author": demo.author.name,
            "indexchar": indexchar
        }
        return self._update_response(url, body)
    
    def search(self, keyword, froms):
        url = "{}/user/{}/{}".format(ES_URL, urls_key, "_search")
        body = {
            "from": froms,
            "size": 8,
            "query": {
                "multi_match": {
                    "query": keyword,
                    "fields": ["title", "content", "indexchar"]
                }
            },
            "highlight": {
                "fields": {
                    "title": {},
                    "content": {},
                }
            }
        }
        return self._search_response(url, body)
